package com.example.star.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.star.R;
import com.example.star.api_service.ApiPerimeter;
import com.example.star.entity.Perimeter;
import com.example.star.retrofit.ApiClient;
import com.example.star.adapter.PerimeterAdapter;
import com.example.star.view.activity.PerimeterDetailActivity;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

// 明星周边 Fragment
public class PerimeterFragment extends Fragment {
    private ListView listView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private PerimeterAdapter adapter;
    private EditText searchEditText;
    private Button searchButton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_perimeter, container, false);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        listView = view.findViewById(R.id.list_view_perimeter);
        searchEditText = view.findViewById(R.id.search_edit_text);
        searchButton = view.findViewById(R.id.search_button);

        // 监听搜索按钮点击事件
        searchButton.setOnClickListener(v -> {
            String keyword = searchEditText.getText().toString();
            if (adapter != null) {
                adapter.filter(keyword);
            }
        });

        // 触发首次数据获取
        perimeter();

        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 检查列表是否在最顶部
            if (isListViewAtTop()) {
                // 触发刷新时重新获取数据
                perimeter();
            } else {
                // 如果不在最顶部，取消刷新
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getContext(), "请先滑动到顶部", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置下拉刷新的颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        // 监听 ListView 的滚动事件
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 检查是否可以下拉刷新
                swipeRefreshLayout.setEnabled(isListViewAtTop());
            }
        });
    }

    private boolean isListViewAtTop() {
        return listView.getFirstVisiblePosition() == 0 &&
                (listView.getChildAt(0) == null || listView.getChildAt(0).getTop() >= 0);
    }

    private void perimeter() {
        // 创建实例
        ApiPerimeter apiPerimeter = ApiClient.getApiPerimeter();
        // 发起查询所有周边数据的网络请求
        Call<List<Perimeter>> call = apiPerimeter.getPerimeters();

        call.enqueue(new Callback<List<Perimeter>>() {
            @Override
            public void onResponse(Call<List<Perimeter>> call, Response<List<Perimeter>> response) {
                if (response.isSuccessful()) {
                    List<Perimeter> perimeters = response.body();
                    if (perimeters != null) {
                        adapter = new PerimeterAdapter(requireContext(), R.layout.item_perimeter, perimeters);
                        listView.setAdapter(adapter);

                        // 设置 ListView 的点击监听器
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                try {
                                    Perimeter perimeter = perimeters.get(position);
                                    Intent intent = new Intent(requireContext(), PerimeterDetailActivity.class);
                                    intent.putExtra("starName", perimeter.getStarName());
                                    intent.putExtra("perimeterTitle", perimeter.getTitle());
                                    intent.putExtra("prices", perimeter.getPrices());
                                    intent.putExtra("imageResource", perimeter.getImageResource());
                                    intent.putExtra("productType", perimeter.getProductType());
                                    intent.putExtra("freight", perimeter.getFreight());
                                    intent.putExtra("deliveryAddress", perimeter.getDeliveryAddress());
                                    startActivity(intent);
                                } catch (NullPointerException e) {
                                    Toast.makeText(requireContext(), "数据异常，请稍后重试", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                } else {
                    Toast.makeText(requireContext(), "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<List<Perimeter>> call, Throwable t) {
                Toast.makeText(requireContext(), "网络请求出错: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        listView = null;
        swipeRefreshLayout = null;
        searchEditText = null;
        searchButton = null;
    }
}